package com.base.cn.platform.os.service.user.integral;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.user.integral.IntegralRuleDao;
import com.base.cn.platform.os.entity.user.integral.IntegralRule;
import com.base.cn.platform.os.service.manage.config.SysConfigBiz;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * 积分规则
 */
@Service
public class IntegralRuleBiz extends BaseBiz<IntegralRule, IntegralRuleDao> {


    @Autowired
    private SysConfigBiz sysConfigBiz;
    public Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    public Map<String, IntegralRule> integralRuleData(String type) {
        List<IntegralRule> integralRuleList = this.find("status=1 AND type='" + type + "'", null, null);
        integralRuleList.forEach(e -> {
            if (StringUtils.isNotEmpty(e.getValue())) {
                if (e.getIsList()) {
                    Map<String, List<Map<String, String>>> map = gson.fromJson(e.getValue(), new TypeToken<TreeMap<String, List<Map<String, String>>>>() {
                    }.getType());
                    e.setContextList(map.get("list"));
                } else {
                    TreeMap<String, String> map = sysConfigBiz.contextToMap(e.getValue());
                    e.setContextTreeMap(map);
                }
            }
        });
        Map<String, IntegralRule> integralRuleMap = integralRuleList.stream().collect(Collectors.toMap(e -> e.getKey(), e -> e));
        return integralRuleMap;
    }


    /**
     * 根据key 获取积分规则
     * @param key
     * @return
     */
    public IntegralRule getIntegralRuleByKey(String key) {
        IntegralRule integralRule = this.findOne(" `key` ='" + key + "' ", null);
        if (integralRule.getIsList()) {
            Map<String, List<Map<String, String>>> map = gson.fromJson(integralRule.getValue(), new TypeToken<TreeMap<String, List<Map<String, String>>>>() {}.getType());
            List<Map<String, String>> list = map.get("list");
            List<Map<String, String>> mapList = list.stream().sorted(Comparator.comparing(e -> Integer.valueOf(e.get("unit")))).collect(Collectors.toList());
            integralRule.setContextList(mapList);
        }else{
            TreeMap<String, String> map = sysConfigBiz.contextToMap(integralRule.getValue());
            integralRule.setContextTreeMap(map);
        }
        return integralRule;
    }

}
